<template>
  <div id="amap-input-container">
    <el-select 
      v-model="searchValue" 
      id="search-select" 
      clearable 
      filterable 
      :filter-method="selectFilter" 
      @change="selectChange" 
      value-key="full" 
      >
        <el-option
        v-for="item in options"
        :key="item.full"
        :label="item.full"
        :value="item">
        </el-option>
    </el-select>
  </div>
</template>
<script>
  const AMap = window.AMap;
  export default {
    name: 'AMap',
    props: {
      value: {
        type: String,
        default:'',
      },
    },
    data() {
      return {
        defaultCity: '厦门',
        // 地图对象
        map: null,
        // 检索关键字
        searchValue: this.value,
        options:undefined,
        autoitem:{}
      };
    },
    watch: {
      value(newVal) {
        this.searchValue = newVal;
      },
      searchValue(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.$emit("input", this.searchValue);
        }
        if('' == newVal || undefined == newVal || null == newVal){
          this.options = [];
        }
      }
    },
    mounted() {
      // 初始化地图页面
      this.initMap();
    },
    beforeDestroy() {
      // 销毁地图
      this.map.destroy();
    },
    methods: {
      //   初始化地图页面
      initMap() {
        this.map = new AMap.Map('custom-amap', {
          resizeEnable: true,
          zoom: 50
        });
        // 添加检索提示
        this.addAMapAutocompletePlaceSearch();
      },
      // 添加检索提示检索
      addAMapAutocompletePlaceSearch() {
        // 自动提示
        this.map.plugin('AMap.AutoComplete', () => {
          this.autoitem = new AMap.Autocomplete({
            city: this.defaultCity,
          });
        });
      },
      // 选择自动提示数据事件回调
      selectChange(e) {
        this.searchValue = e.full;
        this.$emit('getPosition', e);
      },
      selectFilter(val){
          let that = this;
          this.autoitem.search(val,function(status,result){
            var resultTips = result.tips.map(function(item){
                var preStr = item.district + item.address;
                if('' == preStr || undefined == preStr){
                    item.full = item.name;
                }else{
                    item.full = preStr + '-' + item.name;
                }
                return item;
            });
            that.options = resultTips;
          });
          this.$emit("input",val);
      },
    }
  };
</script>

<style lang="scss">
.el-select {
  width:100%;
}
</style>